package cn.deali.homework9.activity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.jaeger.library.StatusBarUtil;
import com.squareup.picasso.Picasso;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.circlenavigator.CircleNavigator;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import cn.deali.homework9.MainApp;
import cn.deali.homework9.service.MusicService;
import cn.deali.homework9.R;
import cn.deali.homework9.adapter.PlayingViewPagerAdapter;
import cn.deali.homework9.model.Music;

public class NowPlayingActivity extends AppCompatActivity {
    private static final String TAG = "NowPlayingActivity";

    Handler seekHandler = new Handler();
    // 进度条下面的当前进度文字，将毫秒化为m:ss格式
    SimpleDateFormat time = new SimpleDateFormat("m:ss");

    //还没做：音乐时长、上一首、下一首、专辑图片的获取
    ViewPager viewPager;
    ImageButton playBtn;
    ImageButton previousBtn;
    ImageButton nextBtn;
    TextView textViewName;
    TextView textViewArtist;
    TextView textViewCurrentTime;
    TextView textViewTotalTime;
    SeekBar seekBar;
    LinearLayout rootLayout;
    MusicService.MusicBinder musicBinder;

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
            // 设置当前播放的文件
            musicBinder.loadFile(MainApp.getInstance().getCurrentMusic().getFilepath());
            seekBar.setMax(musicBinder.getProgress());
            textViewTotalTime.setText(time.format(musicBinder.getProgress()));
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    // 这里很重要，如果不判断是否来自用户操作进度条，会不断执行下面语句块里面的逻辑，然后就会卡顿卡顿
                    if (fromUser) {
                        musicBinder.seekToPositon(seekBar.getProgress());
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            // 设置播放进度条更新线程
            seekHandler.post(mRunnable);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    /**
     * 更新ui的runnable
     */
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            seekBar.setProgress(musicBinder.getPlayPosition());
            textViewCurrentTime.setText(time.format(musicBinder.getPlayPosition()));
            seekHandler.postDelayed(mRunnable, 1000);
        }
    };

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            LinearLayout rootLayout = findViewById(R.id.root_layout);
            Bitmap bitmap = (Bitmap) msg.obj;
            rootLayout.setBackground(new BitmapDrawable(NowPlayingActivity.this.getResources(), bitmap));
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        setContentView(R.layout.activity_now_playing);
        StatusBarUtil.setTranslucent(NowPlayingActivity.this, 0);//设置状态栏透明

        textViewName = findViewById(R.id.name);
        textViewArtist = findViewById(R.id.singer);
        rootLayout = findViewById(R.id.root_layout);
        playBtn = findViewById(R.id.playBtn);
        previousBtn = findViewById(R.id.previousBtn);
        nextBtn = findViewById(R.id.nextBtn);
        textViewCurrentTime = findViewById(R.id.tvCurrentTime);
        textViewTotalTime = findViewById(R.id.tvTotalTime);
        seekBar = findViewById(R.id.musicSeekBar);

        //服务
        Intent intent = new Intent(NowPlayingActivity.this, MusicService.class);
        startService(intent);//开始服务，退出页面后仍然服务
        bindService(intent, connection, Service.BIND_AUTO_CREATE);

        // 更新当前播放信息
        updateCurrentMusic();

        //mTitleDataList.size用来设置圆点个数
        final ArrayList<String> mTitleDataList = new ArrayList<>();
        mTitleDataList.add("专辑");
        mTitleDataList.add("歌词");

        //渲染view_pager
        viewPager = findViewById(R.id.view_pager);
        PlayingViewPagerAdapter adapter = new PlayingViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);

        //指示器
        final MagicIndicator magicIndicator = findViewById(R.id.magic_indicator);
        CircleNavigator circleNavigator = new CircleNavigator(this);
        circleNavigator.setCircleCount(mTitleDataList.size());
        circleNavigator.setCircleColor(Color.WHITE);
        //点击圆点切换fragment
        circleNavigator.setCircleClickListener(new CircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {
                viewPager.setCurrentItem(index);
            }
        });
        magicIndicator.setNavigator(circleNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);//绑定viewPager和指示器,切换fragment圆点也会有对应变化
    }


    @Override
    protected void onDestroy() {
        seekHandler.removeCallbacks(mRunnable);
        musicBinder.closePlayer();
        super.onDestroy();
    }

    public void updateCurrentMusic() {
        Music currentMusic = MainApp.getInstance().getCurrentMusic();
        // 设置数据
        if (currentMusic.getImgData() != null)
            rootLayout.setBackground(new BitmapDrawable(this.getResources(), currentMusic.getImgData()));
        else
            new GetAlbumPicThread().start();
        textViewName.setText(currentMusic.getName());
        textViewArtist.setText(currentMusic.getArtist());
    }


    //更新按钮图标
    public void updatePlayBtn() {
        if (musicBinder.isPlaying()) {
            playBtn.setImageResource(R.drawable.ic_play_btn_play);
        } else {
            playBtn.setImageResource(R.drawable.ic_play_btn_pause_pressed);
        }
    }

    //点击按钮播放/暂停音乐
    public void onPlayBtnClick(View view) {
        Log.i(TAG, MainApp.getInstance().getCurrentMusic().getFilepath());
        musicBinder.play();
        updatePlayBtn();
    }

    //点击按钮下一首
    public void onNextBtnClick(View view) {
        musicBinder.reset();
        boolean result = MainApp.getInstance().next();
        if (!result) {
            Toast.makeText(this, "没有下一首可以播放了！", Toast.LENGTH_SHORT).show();
            return;
        }
        onPlayBtnClick(view);
        updateCurrentMusic();
    }

    //点击按钮上一首
    public void onPreviousBtnClick(View view) {
        musicBinder.reset();
        boolean result = MainApp.getInstance().previous();
        if (!result) {
            Toast.makeText(this, "没有上一首可以播放了！", Toast.LENGTH_SHORT).show();
            return;
        }
        onPlayBtnClick(view);
        updateCurrentMusic();
    }

    class GetAlbumPicThread extends Thread {
        @Override
        public void run() {
            super.run();
            Bitmap musicPic = null;
            try {
                musicPic = Picasso.get().load(MainApp.getInstance().getCurrentMusic().getImgUrl()).get();
            } catch (IOException ex) {
                Log.e(TAG, ex.getMessage());
            }

            MainApp.getInstance().getCurrentMusic().setImgData(musicPic);

            Message message = new Message();
            message.obj = musicPic;
            handler.sendMessage(message);
        }
    }
}
